// src/utils/http.ts
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'

// 定义接口返回的数据结构
interface ApiResponse<T = any> {
  code: number
  successFul: boolean
  message: string
  data: T
}

// post、put 请求数据类型
type DataPayload = Record<PropertyKey, unknown>

class HttpClient {
  private instance: AxiosInstance

  constructor(baseURL: string, withCredentials: boolean = true) {
    this.instance = axios.create({
      baseURL,
      timeout: 10000, // 请求超时时间
      headers: {
        'Content-Type': 'application/json',
      },
      withCredentials: withCredentials, // 是否携带cookie
    })

    // 请求拦截器
    this.instance.interceptors.request.use(
      config => {
        // 在发送请求之前做些什么
        const token = localStorage.getItem('token') // 假设你用localStorage保存token
        if (token && config.headers) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      error => Promise.reject(error),
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse<ApiResponse>) => {
        // 对响应数据做点什么
        if (response.data.successFul) {
          console.error('请求失败:', response.data.message)
          return Promise.reject(response.data.message)
        }
        return response.data.data // 返回data字段的内容
      },
      error => {
        // 对响应错误做点什么
        console.error('请求出错:', error.message)
        return Promise.reject(error)
      },
    )
  }

  public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config)
  }

  public post<T>(url: string, data?: DataPayload, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.post(url, data, config)
  }

  public put<T>(url: string, data: DataPayload = {}, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.put(url, data, config)
  }

  public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config)
  }
}

// 创建并导出实例
export const http = new HttpClient(
  import.meta.env.VITE_APP_API_BASE_URL || 'https://api.example.com',
)
